package com.chcit.mobile.mvp.inventory.fragment.pandian;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import com.google.android.material.tabs.TabLayout;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import com.xuexiang.xui.widget.dialog.materialdialog.MaterialDialog;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chcit.custom.view.edit.SuperInputEditText;
import com.chcit.custom.view.loader.LoaderStyle;
import com.chcit.custom.view.loader.QuickLoader;
import com.chcit.custom.view.util.DialogUtil;
import com.chcit.mobile.R;
import com.chcit.mobile.app.base.ScanFragment;
import com.chcit.mobile.di.component.DaggerInventoryPlanHandleComponent;
import com.chcit.mobile.di.module.InventoryPlanHandleModule;
import com.chcit.mobile.helper.HttpClientHelper;
import com.chcit.mobile.mvp.common.adapter.PackageScanAdapter;
import com.chcit.mobile.mvp.inventory.contract.InventoryPlanHandleContract;
import com.chcit.mobile.mvp.inventory.entity.InventoryPackageBean;
import com.chcit.mobile.mvp.inventory.presenter.InventoryPlanHandlePresenter;
import com.chcit.mobile.mvp.entity.PackageBean;
import com.jess.arms.di.component.AppComponent;
import com.jess.arms.utils.ArmsUtils;
import com.xuexiang.xui.widget.toast.XToast;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.Objects;
import butterknife.BindView;
import butterknife.OnClick;
import static com.jess.arms.utils.Preconditions.checkNotNull;


public class InventoryPackagePlanHandleFragment extends ScanFragment<InventoryPlanHandlePresenter> implements InventoryPlanHandleContract.View {

    @BindView(R.id.tiet_ipph_no)
    SuperInputEditText tietNo;
    /*@BindView(R.id.til_ipph_no)
    TextInputLayout tilNo;*/
    @BindView(R.id.tv_ipph_productname)
    TextView tvProductname;
    @BindView(R.id.tv_ipph_lot)
    TextView tvLot;
    @BindView(R.id.tv_ipph_productCode)
    TextView tvProductCode;
    @BindView(R.id.tv_ipph_productSpec)
    TextView tvProductSpec;
    @BindView(R.id.tv_ipph_manufacturer)
    TextView tvManufacturer;
    @BindView(R.id.tv_ipph_qtyBook)
    TextView tvQtyBook;
    @BindView(R.id.tv_ipph_qtyDiff)
    TextView tvQtyDiff;
    @BindView(R.id.tv_ipph_qtyPakcageBook)
    TextView tvQtyPackageBook;
    @BindView(R.id.tv_ipph_qtyPakcageDiff)
    TextView tvQtyPakcageDiff;
    @BindView(R.id.tv_ipph_locator)
    TextView tvLocator;
    @BindView(R.id.rv_receive_list)
    RecyclerView mRecyclerView;
    @BindView(R.id.tl_tabs)
    TabLayout tlTabs;
    private InventoryPackageBean storageBean = null;
    private String reasonId = null;
    private PackageScanAdapter doneScanAdapter;
    private List<PackageBean> donePackageBeans = new ArrayList<>();
    private PackageBean packageBean;
    private PackageScanAdapter unScanAdapter;
    private BigDecimal qtyCount = BigDecimal.ZERO;
    private BigDecimal qtyDiff;
    private BigDecimal qtyPackageBook ,qtyPackageDiff;

    public static InventoryPackagePlanHandleFragment newInstance(InventoryPackageBean storageBean) {
        InventoryPackagePlanHandleFragment fragment = new InventoryPackagePlanHandleFragment();
        fragment.storageBean = storageBean;
        return fragment;
    }

    @Override
    public void setupFragmentComponent(@NonNull AppComponent appComponent) {
        DaggerInventoryPlanHandleComponent //如找不到该类,请编译一下项目
                .builder()
                .appComponent(appComponent)
                .inventoryPlanHandleModule(new InventoryPlanHandleModule(this))
                .build()
                .inject(this);
    }

    @Override
    public View initView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_inventory_package_plan_handle, container, false);
    }

    @Override
    public void initData(@Nullable Bundle savedInstanceState) {
        mCommonToolbar.setTitleText("盘点处理");
        mCommonToolbar.getLeftMenuView(0).setOnClickListener(l -> {
            pop();
        });
        initShowData();
    }


    @Override
    public void setData(@Nullable Object data) {

    }

    @Override
    public void showLoading() {
        QuickLoader.showLoading(mContext,LoaderStyle.SemiCircleSpinIndicator);
    }

    @Override
    public void hideLoading() {
        QuickLoader.stopLoading();
    }

    @Override
    public void showMessage(@NonNull String message) {
        checkNotNull(message);
         XToast.info(mContext,message).show();
    }

    @Override
    public void launchActivity(@NonNull Intent intent) {
        checkNotNull(intent);
        ArmsUtils.startActivity(intent);
    }

    @Override
    public void killMyself() {
       pop();
    }


    @OnClick({R.id.bt_ipph_cancel, R.id.bt_ipph_ok})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.bt_ipph_ok:
                JSONObject param = new JSONObject();
                JSONArray planLines = new JSONArray();
                planLines.add(storageBean.getInventoryPlanLineId());
                param.put("inventoryPlanLineId",planLines);
                assert mPresenter != null;
                mPresenter.doChecked(param,()->{
                    showMessage("操作成功！");
                    setFragmentResult(RESULT_OK,null);
                    pop();
                },mContext);
                break;
            case R.id.bt_ipph_cancel:
             /*
           packageNo:["213123213","1231231"]
           inventoryPlanId:1000130
         */


                JSONObject data = new JSONObject();
                data.put("inventoryPlanId", storageBean.getInventoryPlanId());
                if(donePackageBeans.size()<1){
                    DialogUtil.showErrorDialog(mContext,"包装不能为空!");
                    return;
                }
                JSONArray packageNo = new JSONArray();
                for(PackageBean p :donePackageBeans){
                    packageNo.add(p.getPackageNo());
                }
                data.put("packageNo", packageNo);
                assert mPresenter != null;
                mPresenter.doConfirmPackage(data, () -> {
                    showMessage("操作成功！");
                    setFragmentResult(RESULT_OK,null);
                    pop();
                });
                break;
        }
    }

    private void initShowData() {
        qtyPackageBook = storageBean.getPackageQtyBook();
        qtyPackageDiff = storageBean.getPackageQtyDiff(); //.subtract(storageBean.getPackageQtyBook())
        qtyDiff = storageBean.getQtyDiff(); //.subtract(storageBean.getQtyBook());
        tvProductname.setText(storageBean.getProductName());
        tvProductSpec.setText(storageBean.getProductSpec());
        tvManufacturer.setText(storageBean.getManufacturer());
        tvQtyPackageBook.setText(String.valueOf(storageBean.getPackageQtyBook()));
        tvLot.setText(storageBean.getLot());
        tvQtyPakcageDiff.setText(qtyPackageDiff.toString());
        tvLocator.setText(storageBean.getLocatorValue());
        tvQtyDiff.setText((qtyDiff+storageBean.getUomName()));
        tvQtyBook.setText((storageBean.getQtyBook()+storageBean.getUomName()));
        tvProductCode.setText(storageBean.getProductCode());
        /* etInvoiceNo.setText(storageBean.getTaxInvoiceNo());*/

    }

    @Override
    protected void onBarcodeEventSuccess(String barcodeData) {
        tietNo.setText(barcodeData);
        checkPackageNo(barcodeData);
    }
    private void checkPackageNo(String packageNo) {
        if (tlTabs.getSelectedTabPosition() != 0) {
            Objects.requireNonNull(tlTabs.getTabAt(0)).select();
        }
        packageBean = new PackageBean(packageNo);
        packageBean.setUnitPackQty(new BigDecimal(storageBean.getUnitPackQty()));
        int itemPosition = unScanAdapter.getData().indexOf(packageBean);;
        if (itemPosition >= 0) {
            if (qtyDiff.intValue() >= 0) {
                DialogUtil.showErrorDialog(mContext,"包装已经扫完！");
                return;
            }
            packageBean = unScanAdapter.getData().get(itemPosition);
            doneScanAdapter.addData(packageBean);
            unScanAdapter.remove(itemPosition);
            updateAddPackageInfo(packageBean);
        } else if ((itemPosition = donePackageBeans.indexOf(packageBean)) >= 0) {
            final int i = itemPosition;
            new MaterialDialog.Builder(mContext)
                    .content("该包装已扫过，是否删除改包装？")
                    .positiveText("否")
                    .negativeText("是")
                    .onNegative((dialog, which) -> {
                        packageBean = donePackageBeans.get(i);
                        unScanAdapter.addData(packageBean);
                        doneScanAdapter.remove(i);
                        updateSubstractPackageInfo(packageBean);
                    }).show();
        } else {
            DialogUtil.showErrorDialog(mContext,"该包装不是在库包装");

        }

    }
    /**
     * 增加包装
     * @param packageBean 包装信息
     */
    @SuppressLint("SetTextI18n")
    private void updateAddPackageInfo(PackageBean packageBean) {
        qtyPackageBook = qtyPackageBook.add(new BigDecimal(1));
        qtyPackageDiff = qtyPackageDiff.add(new BigDecimal(1));
        qtyCount = qtyCount.add(packageBean.getQty());
        qtyDiff = qtyDiff.add(packageBean.getQty());
        //tvQtyPackageBook.setText(qtyPackageBook.toString());
        //tvQtyBook.setText(qtyBook.toString() + storageBean.getUomName());
        tvQtyPakcageDiff.setText(qtyPackageDiff.toString());
        tvQtyDiff.setText(qtyDiff.toString() + storageBean.getUomName());
    }

    /**
     * 移除包装
     *
     * @param packageBean 包装信息
     */
    @SuppressLint("SetTextI18n")
    private void updateSubstractPackageInfo(PackageBean packageBean) {
        qtyPackageBook = qtyPackageBook.subtract(new BigDecimal(1));
        qtyPackageDiff = qtyPackageDiff.subtract(new BigDecimal(1));
        qtyCount = qtyCount.add(packageBean.getQty());
        qtyDiff = qtyDiff.subtract(packageBean.getQty());
       // tvQtyPackageBook.setText(qtyPackageBook.toString());
       // tvQtyBook.setText(qtyBook.toString() + storageBean.getUomName());
        tvQtyPakcageDiff.setText(qtyPackageDiff.toString());
        tvQtyDiff.setText(qtyDiff.toString() + storageBean.getUomName());

    }

    @Override
    public void onEnterAnimationEnd(Bundle savedInstanceState) {
        super.onEnterAnimationEnd(savedInstanceState);
        initDoneScanRecyclerView();
        initUnScanRecyclerView();
        getData();
        initEvent();

    }

    private void initEvent() {
        tietNo.setOnKeyListener(new View.OnKeyListener() {
            private static final int LIMIT_TIME = 300;
            private long lastClickTime = 0;

            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                long curTime = Calendar.getInstance().getTimeInMillis();
                if (curTime - lastClickTime > LIMIT_TIME) {
                    lastClickTime = curTime;
                    if (keyCode == KeyEvent.KEYCODE_ENTER && !Objects.requireNonNull(tietNo.getText()).toString().isEmpty()) {
                        onBarcodeEventSuccess(tietNo.getText().toString());
                        return true;
                    } else {
                        return false;
                    }

                }
                return false;

            }
        });
        tlTabs.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {

            @Override
            public void onTabSelected(TabLayout.Tab tab) {

                switch (tab.getPosition()) {
                    case 0:
                        mRecyclerView.setAdapter(doneScanAdapter);
                        break;
                    case 1:

                        mRecyclerView.setAdapter(unScanAdapter);
                        break;
                }

            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {

            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {

            }
        });

    }

    private void getData() {
        JSONObject data = new JSONObject();
                            /*pageNum:1
                            pageSize:25
                            limit:25
                            start:0
                            warehouseId:1000220
                            warehouseId_text:药剂科
                            productName:2032
                            lot:fdfk54
                            unitPackQty:10
                            packageStatus:S
                            packageStatus_text:在库
                            recievedDays:0*/
        data.put("start", 0);
        data.put("limit", 500);
        data.put("warehouseId", HttpClientHelper.getSelectWareHouse().getId());
        data.put("productName", storageBean.getProductCode());
        if(storageBean.getLot()!= null){
            data.put("lot", storageBean.getLot());
        }
        data.put("unitPackQty", storageBean.getUnitPackQty());
        data.put("packageStatus","S");
        assert mPresenter != null;
        mPresenter.getPakcageInfo(data, list -> {
            unScanAdapter.addData(list);
            //mRecyclerView.setAdapter(unScanAdapter);
        });

    }


    /*  pageNum:1
      pageSize:25
      limit:25
      start:0
      warehouseId:1000220
      warehouseId_text:药剂科
      productName:2032
      lot:fdfk54
      unitPackQty:10
      packageStatus:S
      packageStatus_text:在库
      recievedDays:0*/
    private void initDoneScanRecyclerView() {
        doneScanAdapter = new PackageScanAdapter(donePackageBeans);
        //ArmsUtils.configRecyclerView(mRecyclerView, mLayoutManager);
        mRecyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
        //  mRecyclerView.addItemDecoration(new RecycleViewDivider(getContext(), LinearLayoutManager.HORIZONTAL, R.drawable.item_drivide));

        doneScanAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            int itemClickPosition = -1;

            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                if (itemClickPosition >= 0) {
                    doneScanAdapter.notifyItemChanged(doneScanAdapter.getthisPosition());
                    doneScanAdapter.setThisPosition(position);
                    itemClickPosition = position;
                    // PackageBean packageBean= (PackageBean) adapter.getData().get(position);
                    doneScanAdapter.notifyItemChanged(doneScanAdapter.getthisPosition());
                }

            }
        });
        doneScanAdapter.setOnclickListener((v, position) -> {
            unScanAdapter.addData(v);
            updateSubstractPackageInfo(v);
            doneScanAdapter.remove(position);

        });
        mRecyclerView.setAdapter(doneScanAdapter);
        
    }
    private void initUnScanRecyclerView() {
        unScanAdapter = new PackageScanAdapter(new ArrayList<>());
        //ArmsUtils.configRecyclerView(mRecyclerView, mLayoutManager);
        mRecyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
        //  mRecyclerView.addItemDecoration(new RecycleViewDivider(getContext(), LinearLayoutManager.HORIZONTAL, R.drawable.item_drivide));

        unScanAdapter.setOnItemClickListener((adapter, view, position) -> {
            if(unScanAdapter.getthisPosition() >=0){
                unScanAdapter.notifyItemChanged(unScanAdapter.getthisPosition());
            }
            unScanAdapter.setThisPosition(position);
            PackageBean packageBean =  unScanAdapter.<PackageBean>getData().get(position);

            unScanAdapter.notifyItemChanged(unScanAdapter.getthisPosition());
            new MaterialDialog.Builder(mContext)
                    .content("确认拣该包装吗？")
                    .positiveText("确定")
                    .negativeText("取消")
                    .onPositive((dialog, which) -> onBarcodeEventSuccess(packageBean.getPackageNo())).show();
        });


    }
}
